package com.yipingnai.blog.task;

import com.yipingnai.blog.model.PV;
import com.yipingnai.blog.service.ArticleService;
import com.yipingnai.blog.service.PVService;
import com.yipingnai.blog.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: 一瓶奶
 * @Url: www.yipingnai.cn
 * @Date: 2020/6/19 17:25
 */
@Component
public class ScheduledTasks {

    @Autowired
    PVService pvService;

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ArticleService articleService;
    // 每天的0点、13点、18点、21点都执行一次：0 0 0,9,13,18,21 * * ?
    // 每分钟执行一次0 */1 * * * ?
    @Scheduled(cron = "0 0 0,9,13,18,21 * * ?")
    public void syncArticleView(){
        Map blogMap = redisUtils.getFieldValueByKey("blogpv");
        int count = 0;
        if(blogMap !=null) {
            Iterator<Map.Entry<String, Integer>> iterator = blogMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, Integer> next = iterator.next();
                int view = next.getValue();
                String key = next.getKey();
                int i = key.toString().lastIndexOf(":");
                int aid  = Integer.parseInt(key.substring(i + 1));
                count += view;
                // 根据id 修改阅读量
                boolean b = articleService.updateViewById(aid, view);
            }
            // 将总pv存到pv表
            // 先查找是否已经存在当天的pv
            if(count > 0){
                PV pv = pvService.getPvByDate(new Date());
                if(pv == null){
                    PV pv1 = new PV();
                    // 新增pv
                    pv1.setPvDate(new Date());
                    pv1.setPageView(count);
                    pvService.addPv(pv1);
                }else{
                    // 修改当天的pageView
                    pvService.updatePvPageViewById(pv.getId(),count);

                }
            }
        }

        // 清空
        redisUtils.delKey("blogpv");
        System.out.println("同步文章阅读量成功~");
    }
}
